from types import *
from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import robot_abstract
from waveapi import ops
from waveapi import document
from waveapi.simplejson import encoder


################################################################################

Robot_Image_URL = 'http://robomosa.appspot.com/image/icon.png'
Robot_Profile_URL = 'http://robomosa.appspot.com/_wave/robot/profile' 
Robot_Version = '1'
Robot_Name = 'Robota'

#######################################################
rep_table = {
    'good' : 'GOOD',
    'bad' : 'bad',
    'wave' : 'wave'
    }


################################################################################

def OnParticipantsChanged(properties, context):
    # Invoked when any participants have been added/removed.
    added = properties['participantsAdded']
    for p in added:
        Notify(context, p)


def Notify(context, participant):
    root_wavelet = context.GetRootWavelet()
    title = root_wavelet.GetTitle()
    submitter = root_wavelet.GetCreator()
    strv = "The title is: " + title.encode('utf-8') + ".\n"
    strv = strv + "Submitter is: " + submitter.encode('utf-8') + ".\n"
    strv = strv + "And, " + participant.encode('utf-8') + " appears just one second ago.\n"
    #root_wavelet.CreateBlip().GetDocument().SetText( strv )


def WalkBlips(context, pbid):
    oblip = context.GetBlipById(pbid)
    if type(oblip) is NoneType :
        return

    odoc = oblip.GetDocument()
    if type(odoc) is not NoneType :
        odoc.AppendText("\n...by Robota...")

    bids = oblip.GetChildBlipIds()
    for bid in bids:
        WalkBlips(context, bid)


def WalkContext(context):
    ############################################################################
    # Approach #1 to traverse the tree... doesn't work
    blips = context.GetBlips()
    for blip in blips:
        blip.GetDocument().AppendText("\n...inspected by Robota, blah blah...")
    ############################################################################
    # Approach #2 to traverse the tree... doesn't work neither...
    #waves = context.GetWaves()
    #for wave in waves:
    #    wavelate_ids = wave.GetWaveletIds()
    #    for wavelateid in wavelate_ids:
    #        wavelate = context.GetWaveletById(wavelateid)
    #        blipid = wavelate.GetRootBlipId()
    #        WalkBlips(context, blipid)


def OnRobotAdded(properties, context):
    # Invoked when the robot has been added.
    WalkContext(context)
    #root_wavelet = context.GetRootWavelet()
    #root_wavelet.CreateBlip().GetDocument().SetText("Nice to meet you.")
    #blipid = root_wavelet.GetRootBlipId()
    #    context.GetBlipById(blipid).GetDocument().AppendText("\n...root inspected...")
    #    blips = context.GetBlips()
    #    for blip in blips:
    #        blip.GetDocument().AppendText("\n...blip inspected...")
    
    # ref: http://wave-samples-gallery.appspot.com/about_app?app_id=60017
    # Robot  creates wave!
    blip = context.GetBlipById(properties['blipId'])
    blipDoc = blip.GetDocument()
    text = blipDoc.GetText()
    if len(text) > 2: 
        newWave = robot_abstract.NewWave(context, context.GetRootWavelet().GetParticipants())
        newWave.SetTitle("New Wave")
        newRootBlipId = newWave.GetRootBlipId()
        newRootBlip  = context.GetBlipById(_newRootBlipId)
        blipDoc = newRootBlip.GetDocument()
    blipDoc.SetText('Welcome to submitty bot')

def OnDocumentChanged(properties, context):
    wavelet = context.GetRootWavelet()
    dataDoc = wavelet.GetDataDocument('_new_ids_')
    if dataDoc and len(dataDoc) > 1:
        waveId = dataDoc.split(' ')[0][1:]
        if waveId != wavelet.GetWaveId():
            newDoc = wavelet.CreateBlip().GetDocument()
            message = 'This wave had content, so I\'ve created a new wave:'
            newDoc.SetText(message)
        newDoc.AppendText('Go')
        newDoc.SetAnnotation(document.Range(len(message), len(message) + 2), 'link/wave', waveId)
        wavelet.SetDataDocument('_new_ids_', '')



def OnBlipSubmitted(properties, context):
    blip = context.GetBlipById(properties['blipId'])
    doc = blip.GetDocument()
    text = doc.GetText()
    occurrences = range(0)
    for rep in rep_table:
        start = 0
        while text.find(rep, start) != -1:
            start = text.find(rep, start)
            occurrences.append( [start, len(rep), rep_table[rep]] )
            start += 1
    occurrences = sorted(occurrences)
    occurrences.reverse()
    for occurrence in occurrences:
        doc.SetTextInRange(document.Range(occurrence[0], occurrence[0]+occurrence[1]), occurrence[2])
        doc.SetAnnotation(document.Range(occurrence[0], occurrence[0]+len(occurrence[2])), "style/color", "rgb(255,0,0)")


################################################################################

if __name__ == '__main__':
    myRobot = robot.Robot(
        name = Robot_Name, 
        image_url = Robot_Image_URL, 
        version = Robot_Version, 
        profile_url = Robot_Profile_URL)
    myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
    myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
    myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnDocumentChanged)
    myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
    myRobot.Run()

